package com.tanqidi.arcgisandroid.ui.layerConfig.subLayer.fieldConfig

import android.content.Context
import android.opengl.Visibility
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import com.jaredrummler.android.colorpicker.ColorPickerDialog
import com.jaredrummler.android.colorpicker.ColorShape
import com.tanqidi.arcgisandroid.R
import com.tanqidi.arcgisandroid.base.BaseRecyclerAdapter
import com.tanqidi.arcgisandroid.base.RecyclerViewHolder
import com.tanqidi.arcgisandroid.base.utils.showToast
import com.tanqidi.arcgisandroid.data.layerConfig.Field
import com.tanqidi.arcgisandroid.data.layerConfig.LayerConfig
import com.tanqidi.arcgisandroid.data.project.Project
import com.tanqidi.arcgisandroid.databinding.FragmentFieldConfigBinding
import com.tanqidi.arcgisandroid.ui.MainActivity
import com.tanqidi.arcgisandroid.ui.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.Observable
import java.util.concurrent.TimeUnit

@AndroidEntryPoint
class FieldConfigFragment : Fragment() {

    private lateinit var binding: FragmentFieldConfigBinding
    private val fieldConfigViewModel by viewModels<FieldConfigViewModel>()
    private val mainViewModel by activityViewModels<MainViewModel>()
    private val args by navArgs<FieldConfigFragmentArgs>()
    //选择颜色的view
    private lateinit var colorView: View
    private var isBorderColor = false
    private lateinit var fieldTypeArrayAdapter: ArrayAdapter<String>
    private lateinit var showTypeArrayAdapter: ArrayAdapter<String>
    private lateinit var styleTypeArrayAdapter: ArrayAdapter<String>
    private val fieldTypeList = listOf(Field.INPUT_TYPE_STRING, Field.INPUT_TYPE_INT, Field.INPUT_TYPE_DOUBLE)
    private val showTypeList = listOf(Field.SHOW_TYPE_INPUT, Field.SHOW_TYPE_SELECT)
    private val styleTypeList = listOf(Field.STYLE_TYPE_SELECT, Field.STYLE_TYPE_CHIP)

    //从本地读取出来的layer对象
    private lateinit var layer: LayerConfig
    private lateinit var project: Project
    private lateinit var fieldAdapter: FieldAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentFieldConfigBinding.inflate(layoutInflater)
        fieldTypeArrayAdapter = ArrayAdapter(requireContext(), R.layout.cat_exposed_dropdown_popup_item, fieldTypeList.toTypedArray())
        showTypeArrayAdapter = ArrayAdapter(requireContext(), R.layout.cat_exposed_dropdown_popup_item, showTypeList.toTypedArray())
        styleTypeArrayAdapter = ArrayAdapter(requireContext(), R.layout.cat_exposed_dropdown_popup_item, styleTypeList.toTypedArray())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        //读取出来project
        project = fieldConfigViewModel.getProjectByName(args.projectName)
        //project有了然后再从project中拿到layer对象
        layer = project.layers.filter { it.name == args.layerName }[0]

        initTopBar()
        initViewEvent()
        initLiveData()
        initData()
        return binding.root
    }

    private fun initData() {
        val recyclerView = binding.recyclerView
        val layoutManager = object : LinearLayoutManager(requireContext()) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        recyclerView.layoutManager = layoutManager
        fieldAdapter = FieldAdapter(requireContext(), layer.fields)
        recyclerView.adapter = fieldAdapter
    }

    private fun initLiveData() {
        mainViewModel.colorLiveData.observe(viewLifecycleOwner) {
            //转16进制，保存进layer
            colorView.setBackgroundColor(it)
            if(isBorderColor){
                layer.borderColor = it
            } else {
                layer.color = it
            }
        }
    }

    private fun initViewEvent() {
        binding.featureLayerUrl.setText(layer.featureLayerUrl)

        when(layer.type) {
            LayerConfig.TYPE_POINT -> {
                //隐藏线宽
                binding.widthTextInputLayout.visibility = View.GONE
                //隐藏颜色选择器
                binding.colorBox.visibility = View.GONE
            }
            LayerConfig.TYPE_POLYLINE -> {
                binding.iconResourceTextInputLayout.visibility = View.GONE
            }
            LayerConfig.TYPE_POLYGON -> {
                binding.iconResourceTextInputLayout.visibility = View.GONE
                //因为是面，所以需要隐藏线宽
                binding.widthTextInputLayout.visibility = View.GONE
                //展示面积
                binding.areaTextInputLayout.visibility = View.VISIBLE
            }
        }

        val toTypedArray = layer.fields.map { it.alias }
        val fieldListAdapter = ArrayAdapter(requireContext(), R.layout.cat_exposed_dropdown_popup_item, toTypedArray)
        binding.labelTextInputLayout.setEndIconOnClickListener {
            binding.label.text = null
            layer.label = "ObjectId"
        }
        //要素标注字段
        binding.label.apply {
            layer.fields.filter { it.field == layer.label }.let {
                if(it.isNotEmpty()){
                    setText(it[0].alias)
                }
            }
            setAdapter(fieldListAdapter)
            setOnItemClickListener { parent, view, position, id ->
                val item = toTypedArray[position]
                val field = layer.fields.filter { it.alias == item }[0]
                layer.label = field.field
            }
        }

        //图片字段
        binding.pictureField.apply {
            layer.fields.filter { it.field == layer.pictureField }.let {
                if(it.isNotEmpty()){
                    setText(it[0].alias)
                }
            }
            setAdapter(fieldListAdapter)
            setOnItemClickListener { parent, view, position, id ->
                val item = toTypedArray[position]
                val field = layer.fields.filter { it.alias == item }[0]
                layer.pictureField = field.field
            }
        }

        //自动识别面积
        binding.areaTextInputLayout.setEndIconOnClickListener {
            binding.area.text = null
            layer.areaField = ""
        }
        binding.area.apply {
            layer.fields.filter { it.field == layer.areaField }.let {
                if(it.isNotEmpty()){
                    setText(it[0].alias)
                }
            }

            setAdapter(fieldListAdapter)
            setOnItemClickListener { parent, view, position, id ->
                val item = toTypedArray[position]
                val field = layer.fields.filter { it.alias == item }[0]
                layer.areaField = field.field
            }
        }

        //唯一值渲染器，图标字段
        binding.iconResourceTextInputLayout.setEndIconOnClickListener {
            binding.label.text = null
            layer.icon = "ObjectId"
        }
        binding.iconResource.apply {
            layer.fields.filter { it.field == layer.icon }.let {
                if(it.isNotEmpty()){
                    setText(it[0].alias)
                }
            }
            setAdapter(fieldListAdapter)
            setOnItemClickListener { parent, view, position, id ->
                val item = toTypedArray[position]
                val field = layer.fields.filter { it.alias == item }[0]
                layer.icon = field.field
            }
        }

        //线宽
        binding.width.apply {
            setText(layer.width.toString())
            addTextChangedListener {
                val content = it.toString().trim()
                if(!TextUtils.isEmpty(content)){
                    layer.width = content.toInt()
                } else {
                    layer.width = 1
                }
            }
        }
        //边框颜色选择器
        binding.borderColor.apply {
            setBackgroundColor(layer.borderColor)
            setOnClickListener {
                colorView = it
                isBorderColor = true
                ColorPickerDialog.newBuilder()
                    .setDialogType(ColorPickerDialog.TYPE_PRESETS)
                    .setAllowPresets(true)
                    .setColorShape(ColorShape.SQUARE)
                    .setDialogId(MainActivity.DIALOG_COLOR_ID)
                    .setColor(layer.borderColor)
                    .setAllowCustom(true)
                    .setShowAlphaSlider(true)
                    .setShowColorShades(true)
                    .show(requireActivity())
            }
        }
        //内容颜色选择器
        binding.contentColor.apply {
            setBackgroundColor(layer.color)
            setOnClickListener {
                colorView = it
                isBorderColor = false
                ColorPickerDialog.newBuilder()
                    .setDialogType(ColorPickerDialog.TYPE_PRESETS)
                    .setAllowPresets(true)
                    .setColorShape(ColorShape.SQUARE)
                    .setDialogId(MainActivity.DIALOG_COLOR_ID)
                    .setColor(layer.color)
                    .setAllowCustom(true)
                    .setShowAlphaSlider(true)
                    .setShowColorShades(true)
                    .show(requireActivity())
            }
        }
    }

    private fun initTopBar() {
        binding.topAppBar.apply {
            setNavigationOnClickListener {
                findNavController().navigateUp()
            }
            setOnMenuItemClickListener {
                when(it.itemId) {
                    R.id.save -> {
                        save()
                        showToast("保存成功")
                    }
                    R.id.add ->{
                        fieldAdapter.add(Field())
                    }
                    R.id.metadata -> {
                        val action = FieldConfigFragmentDirections.actionFieldConfigFragmentToMetadataFragment(args.projectName, args.layerName)
                        findNavController().navigate(action)
                    }
                }
                false
            }
        }

    }

    override fun onPause() {
        super.onPause()
        save()
    }

    private fun save(){
        //在返回页面的时候，重新保存project到本地
        layer.fields = fieldAdapter.data as ArrayList<Field>
        fieldConfigViewModel.saveProject(project)
    }

    private inner class FieldAdapter(context: Context, list: List<Field>) : BaseRecyclerAdapter<Field>(context, list) {
        override fun getItemLayoutId(viewType: Int): Int {
            return R.layout.item_field
        }

        override fun bindData(holder: RecyclerViewHolder, position: Int, item: Field) {
            holder.apply {
                (getView(R.id.alias) as TextInputEditText).apply {
                    setText(item.alias)
                    addTextChangedListener {
                        item.alias = it.toString().trim()
                    }
                }
                (getView(R.id.field) as TextInputEditText).apply {
                    setText(item.field)
                    addTextChangedListener {
                        item.field = it.toString().trim()
                    }
                }
                (getView(R.id.defaultValue) as TextInputEditText).apply {
                    setText(item.defaultValue)
                    addTextChangedListener {
                        item.defaultValue = it.toString().trim()
                    }
                }
                (getView(R.id.type) as AutoCompleteTextView).apply {
                    setText(item.type, false)
                    setAdapter(fieldTypeArrayAdapter)
                    setOnItemClickListener { parent, view, position, id ->
                        item.type = fieldTypeList[position]
                    }
                }
                (getView(R.id.showType) as AutoCompleteTextView).apply {
                    setText(item.showType, false)
                    setAdapter(showTypeArrayAdapter)
                    setOnItemClickListener { parent, view, position, id ->
                        item.showType = showTypeList[position]
                    }
                }
                (getView(R.id.styleType) as AutoCompleteTextView).apply {
                    setText(item.styleType, false)
                    setAdapter(styleTypeArrayAdapter)
                    setOnItemClickListener { parent, view, position, id ->
                        item.styleType = styleTypeList[position]
                    }
                }
                getView(R.id.delete).setOnClickListener {
                    MaterialAlertDialogBuilder(requireContext())
                        .setTitle("提示")
                        .setMessage("确定删除该属性吗?")
                        .setPositiveButton("确定") { dialog, which ->
                            layer.fields.remove(item)
                            remove(absoluteAdapterPosition)
                        }.show().findViewById<TextView>(android.R.id.message)?.setTextColor(requireContext().resources.getColor(R.color.app_color_theme_1))
                }
            }
        }
    }
}